<template>
  <div class="box">
    <iu-header>
      <template #left>
        <x-icon
          @click="back"
          type="ios-arrow-back"
          size="21"
          fill="#fff"
        ></x-icon>
        新增出库单
      </template>
      <template #title> </template>
      <template #right>
       <div v-focusable  @click="backToHomepage">
          <iconSvg name="home" w="20px" h="22px" class="right_icon"></iconSvg>
        </div>
      </template>
    </iu-header>
    <div class="content">
      <ul class="contentUl">
        <div class="cate-nfo">
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">领用部门</span>
            </div>
            <div class="contentRight">
              <organization
                class="changeDep"
                :selectDepartment="curDepartment"
                :treeData="userServiceArea"
                @department_select="departmentSelected"
                ref="department"
                :style="{
                  color: departmentIdshow
                    ? '#fff!important'
                    : '#6f6f77!important'
                }"
              >
              </organization>
            </div>
          </li>
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">安装设备</span>
            </div>
            <div class="contentRight cancelPos">
              <device
                :deviceId="outboundForm.deviceId"
                :departmentId="outboundForm.departmentId"
                :deviceData="deviceData"
                @getDeviceData="getDevice"
                ref="devices"
                :style="{
                  color: deviceIdshow ? '#fff!important' : '#6f6f77!important'
                }"
              ></device>
            </div>
          </li>
        </div>
        <div class="cate-nfo">
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">领用人</span>
            </div>
            <div class="contentRight">
              <fz-people
                class="changeDep"
                :peopleId="outboundForm.departmentId"
                :leader="outboundForm.receiveOperator"
                :peopleData="peopleData"
                :name="'选择领用人'"
                @selectPeople="getPeople"
                ref="people"
                :style="{
                  color: selectPeopleIdshow
                    ? '#fff!important'
                    : '#6f6f77!important'
                }"
              >
              </fz-people>
            </div>
          </li>
        </div>
        <div class="cate-nfo">
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">备件名称</span>
            </div>
            <div class="contentRight border">
              <input
                type="text"
                v-model="outboundForm.sparePartName"
                placeholder="请输入备件名称"
                maxlength="40"
              />
            </div>
          </li>
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">备件型号</span>
            </div>
            <div class="contentRight border">
              <input
                type="text"
                v-model="outboundForm.sparePartModel"
                placeholder="请输入备件型号"
                maxlength="40"
              />
            </div>
          </li>
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">厂家供应商</span>
            </div>
            <div class="contentRight border">
              <input
                type="text"
                v-model="outboundForm.manufacturer"
                placeholder="输入备件厂家或供应商名称"
                maxlength="40"
              />
            </div>
          </li>
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">领出时间</span>
            </div>
            <div class="contentRight border" @click="selectTime">
              <span v-if="outboundForm.outRepertoryTime">
                {{
                  outboundForm.outRepertoryTime | formatDate("YYYY-MM-DD HH:mm")
                }}
              </span>
              <span v-else style="color:gray;font-size:14px">
                选择领出时间
              </span>
              <!-- <input
                type="text"
                v-model="outboundForm.outRepertoryTime"
                placeholder="选择领出时间"
                maxlength="40"
              /> -->
            </div>
          </li>
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">出库数量</span>
            </div>
            <div class="contentRight border">
              <input
                type="text"
                v-model.number="outboundForm.outRepertoryCount"
                placeholder="输入出库数量"
                maxlength="40"
                @blur="checkedNumber"
              />
              <span>件</span>
            </div>
            <span class="err-msg" v-if="errmsg1">{{ errmsg1 }}</span>
          </li>
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">单 价</span>
            </div>
            <div class="contentRight border">
              <input
                type="text"
                v-model.number="outboundForm.price"
                placeholder="输入备件单价"
                maxlength="40"
                @blur="checkedNumber"
              />

              <span>元</span>
            </div>
            <span class="err-msg" v-if="errmsg2">{{ errmsg2 }}</span>
          </li>
          <li class="contentList">
            <div class="contentLeft">
              <span class="notNull">*</span>
              <span class="contentLeftFont">质 保 期</span>
            </div>
            <div class="contentRight border">
              <input
                type="text"
                v-model.number="outboundForm.warrantyPeriod"
                placeholder="输入质保期时间"
                maxlength="40"
                @blur="checkedNumber"
              />
              <span>月</span>
            </div>
            <span class="err-msg" v-if="errmsg3">{{ errmsg3 }}</span>
          </li>
        </div>
        <div class="cate-nfo">
          <li class="contentList full">
            <div class="contentLeft">
              <span class="notNull">&nbsp;</span>
              <span class="contentLeftFont">备注</span>
            </div>
            <div class="contentRight">
              <textarea
                name="userQuestion"
                v-model="outboundForm.remark"
                placeholder="请输入备注"
                class="userQuestion"
                maxlength="200"
                @blur="recovery"
              ></textarea>
            </div>
          </li>
        </div>
        <li class="contentList">
          <button type="button" class="subBtn" @click="cancel">取消</button>
          <button
            type="button"
            class="subBtn"
            :class="{ 'is-edited': !isEdited }"
            :disabled="!isEdited"
            @click="submit"
          >
            保存
          </button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Organization from "@/components/common/replace/sellWorkOrderDepartment";
import fzPeople from "@/components/common/replace/sellWorkOrderPeople";
import device from "@/components/common/replace/device";
// import parts from "@/components/common/parts";
// import priority from "@/components/common/priority";
// import upload from "@/components/common/upload/upload";
import SpotCheckDao from "@/daos/spotCheckDao";
import iuHeader from "@/components/common/header/index";
// import FileUpload from "@/daos/file_upload";
import { Toast, XInput } from "vux";
import dayjs from "dayjs";
export default {
  components: {
    Organization,
    fzPeople,
    iuHeader,
    device,
    // parts,
    // priority,
    Toast,
    XInput
    // upload
  },
  data() {
    return {
      userQuestion: "",
      listValue: 0,
      leader: "",
      departmentId: "", //部门id
      selectPeopleId: "", //处理人id
      getSelectDevice: {}, //获取设备
      departmentIdshow: false,
      selectPeopleIdshow: false,
      deviceIdshow: false,
      partsIdshow: false,
      url: "",
      fileList: [],
      deviceData: [],
      peopleData: [],
      userServiceArea: {},
      loading: false,
      id: 0,
      edit: false,
      errmsg1: "",
      errmsg2: "",
      errmsg3: "",
      errmsg4: "",
      errmsg5: "",
      backupForm: {},
      outboundForm: {
        departmentId: "",
        deviceId: "",
        manufacturer: "",
        orgId: "",
        outRepertoryCount: "",
        outRepertoryTime: "",
        price: "",
        receiveOperator: "",
        remark: "",
        sparePartModel: "",
        sparePartName: "",
        submitOperator: "",
        warrantyPeriod: ""
      },
      curDepartment: {
        departmentName: "选择部门",
        id: -1
      }
    };
  },
  //返回首页的公共方法
  inject: ["backToHomepage"],
  created() {
    this.initDefaultForm();
  },
  computed: {
    user() {
      return this.$store.state.user;
    },
    isEdited() {
      if (
        this.edit &&
        this.backupForm.departmentId === this.outboundForm.departmentId &&
        this.backupForm.deviceId === this.outboundForm.deviceId &&
        this.backupForm.manufacturer === this.outboundForm.manufacturer &&
        this.backupForm.outRepertoryCount ===
          this.outboundForm.outRepertoryCount &&
        this.backupForm.outRepertoryTime ===
          this.outboundForm.outRepertoryTime &&
        this.backupForm.price === this.outboundForm.price &&
        this.backupForm.receiveOperator === this.outboundForm.receiveOperator &&
        this.backupForm.remark === this.outboundForm.remark &&
        this.backupForm.sparePartModel === this.outboundForm.sparePartModel &&
        this.backupForm.sparePartName === this.outboundForm.sparePartName &&
        this.backupForm.submitOperator === this.outboundForm.submitOperator &&
        this.backupForm.warrantyPeriod === this.outboundForm.warrantyPeriod
      ) {
        return false;
      }

      return true;
    }
  },
  methods: {
    recovery() {
      window.scroll(0, 0);
    },
    back() {
      history.back(-1);
    },
    initDefaultForm() {
      if (!this.user) {
        this.getUserInfo();
      } else {
        this.getOutboundOrderUserByDepartment(this.user.department.id);
      }
      this.getUserServiceArea();
    },
    initEdit() {
      this.id = this.$route.query.id || 0;
      if (this.id) {
        this.edit = true;
        this.getOutboundOrderDetails(this.id);
      }
    },
    getUserInfo() {
      this.$http(this.$API.getUserInfo, {}).then(res => {
        this.$store.commit("saveUser", res);
        this.initDefaultForm();
        // this.receiver = this.$store.state.user.id;
        // this.receiverName = this.$store.state.user.name;
      });
    },
    getUserServiceArea() {
      SpotCheckDao.getOutboundOrderUserServiceArea(res => {
        if (res && res.length) {
          let item = {
            departmentName: this.user.serviceAreaTree.departmentName,
            id: this.user.serviceAreaTree.id,
            children: res
          };
          this.userServiceArea = item;
        }
        this.initEdit();
      });
    },
    getOutboundOrderDeviceByDepartment(departmentId) {
      SpotCheckDao.getOutboundOrderDeviceByDepartment(departmentId, res => {
        if (res && res.length) {
          this.deviceData = res;
        }
      });
    },
    getOutboundOrderUserByDepartment(departmentId) {
      SpotCheckDao.getOutboundOrderUserByDepartment(departmentId, res => {
        if (res && res.length) {
          this.peopleData = res;
        }
      });
    },
    getOutboundOrderDetails(id) {
      SpotCheckDao.getOutboundOrderDetails(id, res => {
        if (res) {
          this.outboundForm = res;
          this.backupForm = JSON.parse(JSON.stringify(res));
          this.curDepartment.id = res.departmentId;
          this.curDepartment.departmentName = res.departmentName;
          // this.detail = res;
          this.getOutboundOrderDeviceByDepartment(
            this.outboundForm.departmentId
          );
          // this.getOutboundOrderUserByDepartment(this.outboundForm.departmentId);
        }
      });
    },

    // 点击完成的时候，获取部门数据
    departmentSelected(params) {
      // console.log(params);
      if (!!params.id) {
        this.curDepartment = params;
        this.outboundForm.departmentId = params.id;
        this.outboundForm.receiveOperator = "";
        this.outboundForm.deviceId = "";
        this.$nextTick(e => {
          this.$refs.devices.selectdeviceData = "";
          this.$refs.people.departPeople = " ";
        });
      } else {
        this.outboundForm.departmentId = this.curDepartment.id;
      }
      if (!this.outboundForm.departmentId) {
        this.departmentIdshow = false;
      } else {
        this.departmentIdshow = true;
      }
      /* this.getRecordsData();
            this.getToDealNum(); */
      this.getOutboundOrderDeviceByDepartment(this.outboundForm.departmentId);
    },
    // 当点击完成时，获取处理人
    getPeople(peopleData) {
      if (!!peopleData.id) {
        this.outboundForm.receiveOperator = peopleData.id;
      }
      if (!this.outboundForm.receiveOperator) {
        this.selectPeopleIdshow = false;
      } else {
        this.selectPeopleIdshow = true;
      }
    },
    // 当点击完成时，获取处理人
    selectReceiver(peopleData) {
      if (!!peopleData.id) {
        this.receiver = peopleData.id;
      }
    },
    // 获取设备数据
    getDevice(data) {
      if (!!data.id) {
        this.getSelectDevice = data;
        this.outboundForm.deviceId = data.id || null;
        // 清空部件
        // this.partsId = "";
        // this.$refs.parts.selectPartsName = "";
      }
      if (!data.id) {
        this.deviceIdshow = false;
      } else {
        this.deviceIdshow = true;
      }
    },
    // 获取部件的数据
    getPartsData(data) {
      if (!!data.id) {
        this.partsId = data.id || null;
      }
      if (!data.id) {
        this.partsIdshow = false;
      } else {
        this.partsIdshow = true;
      }
    },
    // 获取优先级
    getPriorityData(data) {
      if (!!data.id) {
        this.priorityId = data.id;
      }
    },

    cancel() {
      this.back();
    },
    checkedNumber(){

      this.errmsg1 = "";
      this.errmsg2 = "";
      this.errmsg3 = "";

      if (!this.isNumber(this.outboundForm.outRepertoryCount)) {
        this.errmsg1 = "请输入整数";
      }
      if (!this.isNumber2(this.outboundForm.price)) {
        this.errmsg2 = "请输入数字, 最多两位小数";
      }
      if (!this.isNumber2(this.outboundForm.warrantyPeriod)) {
        this.errmsg3 = "请输入数字, 最多两位小数";
      }
    },
    submit() {
      // console.log(1);
      let text = "";

      this.errmsg1 = "";
      this.errmsg2 = "";
      this.errmsg3 = "";
      if (!this.outboundForm.departmentId) {
        text = "请选择部门";
      } else if (!this.outboundForm.deviceId) {
        text = "请选择安装设备";
      } else if (!this.outboundForm.receiveOperator) {
        text = "请选择领用人";
      } else if (!this.outboundForm.sparePartName) {
        text = "请输入备件名称";
      } else if (!this.outboundForm.sparePartModel) {
        text = "请输入备件型号";
      } else if (!this.outboundForm.manufacturer) {
        text = "请输入厂家供应商";
      } else if (!this.outboundForm.outRepertoryTime) {
        text = "请选择领出时间";
      }
      if (!this.outboundForm.outRepertoryCount) {
        text = "请输入出库数量";
        this.errmsg1 = "请输入出库数量";
      }
      if (!this.outboundForm.price) {
        text = "请输入备件单价";
        this.errmsg2 = "请输入备件单价";
      }
      if (!this.outboundForm.warrantyPeriod) {
        text = "请输入质保期";
        this.errmsg3 = "请输入质保期";
      }
      if (!this.isNumber(this.outboundForm.outRepertoryCount)) {
        text = "出库数量请输入整数";
        this.errmsg1 = "请输入整数";
      }
      if (!this.isNumber2(this.outboundForm.price)) {
        text = "单价请输入数字";
        this.errmsg2 = "请输入数字, 最多两位小数";
      }
      if (!this.isNumber2(this.outboundForm.warrantyPeriod)) {
        text = "质保期请输入数字";
        this.errmsg3 = "请输入数字, 最多两位小数";
      }
      if (text) {
        // this.$commom.alert(text);
        this.$vux.toast.show({ text, type: "warn" });
        return;
      }
      this.outboundForm.submitOperator = this.user.id;
      // this.outboundForm.warrantyPeriod = +this.outboundForm.warrantyPeriod
      SpotCheckDao.postOutboundOrderSaveOrUpdate(this.outboundForm, res => {
        // 清空所有的值
        // this.$refs.department.curDepartment = "";
        // this.$refs.people.departPeople.id = " ";
        // this.$refs.people.departPeople.mane = " ";
        // this.$refs.devices.selectdeviceData = "";
        this.$vux.toast.show({ text: "保存成功！", type: "success" });
        this.back();
      });

      // this.$http(this.$API.referTo,params,true).then((res)=>{
      // });
    },

    isNumber(source) {
      let flag = /^([0-9]*)$/.test(source);
      // console.log(flag,source);
      return flag;
    },
    isNumber2(source) {
      let flag = /^([0-9]*|\d*\.\d{1,2}?)$/.test(source);
      // console.log(flag,source);
      return flag;
    },
    selectTime(index) {
      let _this = this;
      this.$vux.datetime.show({
        cancelText: "取消",
        confirmText: "确定",
        format: "YYYY-MM-DD HH:mm",
        startDate: "",
        onConfirm(value) {
          _this.outboundForm.outRepertoryTime = dayjs(value);
        },
        onHide(type) {
          if (type === "cancel") {
            // that.banci = value
          }
        }
      });
    },
    saveSellWorkOrder(obj) {
      localStorage.setItem("sellWorkOrder", JSON.stringify(obj));
    },
    getSellWorkOrder(obj) {
      let sellWorkOrder = JSON.parse(localStorage.getItem("sellWorkOrder"));
      return sellWorkOrder;
    }
    // oversize() {
    //   this.$vux.toast.text("文件大小请不要超过5MB。");
    // },
    // overcount() {
    //   this.$vux.toast.text("文件个数请小于10个。");
    // },
    // deleteList(index) {
    //   this.fileList.splice(index, 1);
    // },
    // afterRead(files) {
    //   let formData = new FormData();
    //   formData.append("file", files);
    //   this.loading = true;
    //   FileUpload.upload(
    //     formData,
    //     res => {
    //       // console.log(res);
    //       this.loading = false;
    //       this.fileList.push(res);
    //     },
    //     err => {
    //       this.loading = false;
    //       this.$vux.toast.text(err);
    //     }
    //   );
    // }
  }
};
</script>

<style lang="less" scoped>
textarea::-webkit-input-placeholder {
  color: rgb(111, 111, 119) !important;
}
textarea:-moz-placeholder  {
  color: rgb(111, 111, 119) !important;
}

textarea::-moz-placeholder  {
  color: rgb(111, 111, 119) !important;
}
textarea:-ms-input-placeholder  {
  color: rgb(111, 111, 119) !important;
}

input {
  &::placeholder {
    font-size: 14px;
    color: gray !important;
  }
}
* {
  padding: 0;
  margin: 0;
  list-style: none;
  border: none;
}
html,
body {
  width: 100%;
}
.box {
  width: 100%;
  min-height: 100vh;
  height: 100%;
  background-color: #18182c;
}
.backHistory {
  transform: rotate(90deg);
  -ms-transform: rotate(90deg); /* IE 9 */
  -moz-transform: rotate(90deg); /* Firefox */
  -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
  -o-transform: rotate(90deg);
  line-height: 40px;
  font-size: 25px !important;
  margin-left: 10px;
}
.pageTop {
  height: 40px;
  color: #fff;
  position: fixed;
  height: 40px;
  width: 100%;
  left: 0px;
  top: 0px;
  background-color: #22233f;
  z-index: 9;
  .sellWorkOrder_header_title {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 16px;
  }
}
.content {
  width: 100%;
  height: 100%;
  // overflow-y: auto;
  padding: 0 15px 20px;
  box-sizing: border-box;
  background-color: #18182c;
}
.contentUl {
  width: 100%;
  height: 100%;
}

.cate-nfo {
  height: auto;
  // min-height: calc(~"100vh" - 80px);
  padding: 8px 16px 8px;
  margin: 8px 0;
  border-radius: 8px;
  background-color: #22233f;
}
.contentList {
  padding: 8px 0;
  overflow: hidden;
  // border-bottom: 1px solid #464656;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  &.full {
    flex-wrap: wrap;
    .contentRight {
      width: 100%;
    }
  }
  -webkit-text-size-adjust: 100% !important;
  .err-msg {
    flex: none;
    width: 100%;
    color: #ff2c2c;
    font-size: 12px !important;
    padding-left: 35%;
    -webkit-text-size-adjust: 100% !important;
  }
}

.upload {
  display: flex;
  flex-direction: column;
  // align-items: center;
  justify-content: space-between;
}
.contentLeft,
.contentRight {
  font-size: 17px;
}
.contentLeft {
  color: #ffffff;
  flex: none;
}
.contentRight {
  position: relative;
  color: #fff;
  box-sizing: border-box;
  margin-top: 3px;
  width: 65%;
  // display: flex;
  // justify-content: flex-end;
  &.border {
    border-bottom: 0.026667rem solid #464656;
    display: flex;
    justify-content: space-between;
  }
  input {
    // text-align: right;
    touch-action: none;
    width: 86%;
    border: 0;
    color: #ffffff;
    font-size: 16px;
    margin-right: 4px;
    &.full {
      width: 100%;
    }
  }
}
.cancelPos {
  position: static;
  width: auto !important;
}
.notNull {
  color: #d81e06;
}

.userQuestion {
  font-size: 17px;
  width: 100%;
  height: 100px;
  border-radius: 6px;
  padding: 10px;
  box-sizing: border-box;
  background-color: transparent;
  border: 1px solid #747480;
  color: #fff;
  text-align: left !important;
}
.userQuestion::-webkit-input-placeholder {
  color: #6f6f77;
  text-align: left;
}
.subBtn {
  width: 40%;
  height: 40px;
  line-height: 1;
  padding: 13px 0;
  box-sizing: border-box;
  text-align: center;
  margin: 0 auto;
  border-radius: 13px;
  background-color: #456de6;
  color: #ffffff;
  margin: 0 4%;
  font-size: 17px;
  margin-top: 0;
  &.is-edited {
    color: #d2d2d2;
    background-color: gray;
  }
}
</style>
